package com.sixks.app.mvc.cmd;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author colin
 * @date: 02/03/2014
 * @time: 11:46
 */
public abstract class ImageReaderUtil {
    /**
     * @param imageUrl
     * @return byte array of the file
     */
    public static byte[] getBytesByURL(String imageUrl) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedInputStream bis = null;
        HttpURLConnection urlconnection = null;
        URL url;
        byte[] buf = new byte[1024];
        try {
            url = new URL(imageUrl);
            urlconnection = (HttpURLConnection) url.openConnection();
            urlconnection.connect();
            bis = new BufferedInputStream(urlconnection.getInputStream());
            for (int len; (len = bis.read(buf)) != -1; ) {
                baos.write(buf, 0, len);
            }
            return baos.toByteArray();
        } finally {
            try {
                if (urlconnection != null) {
                    urlconnection.disconnect();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException ignore) {
            }
        }
    }
}
